//
//  MNDSwitchAccountViewController.m
//  minidai
//
//  Created by Vitas on 2018/5/28.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDSwitchAccountViewController.h"
#import "MNDSwitchAccountCell.h"
#import "MNDAddAccountCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MNDLoginViewController.h"
#import "MNDLoginModel.h"
#import "MNDForgotViewController.h"
#import "RSAUtil.h"
#import <UMPush/UMessage.h>

#define kMNDSwitchAccountCell @"MNDSwitchAccountCell"
#define kMNDAddAccountCell @"MNDAddAccountCell"

@interface MNDSwitchAccountViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *iconImageVIew;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property(nonatomic, strong) MNDLoginModel *loginModel;

@end

@implementation MNDSwitchAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.iconImageVIew.layer.cornerRadius = self.iconImageVIew.bounds.size.height * 0.5;
    self.iconImageVIew.clipsToBounds = YES;
    if(self.phoneStr.length == 11) {
        NSString *str = [self.phoneStr stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        self.phoneLabel.text = str;
    }
   
    [self.iconImageVIew sd_setImageWithURL:[NSURL URLWithString:self.iconImageStr]];
    // Do any additional setup after loading the view.
}

//显示隐藏密码
- (IBAction)hideOrShowPasswordAction:(UIButton *)sender {
    
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        [self.passwordTextField setSecureTextEntry:NO];
    } else {
        [self.passwordTextField setSecureTextEntry:YES];
    }
}

//登录
- (IBAction)loginAction:(UIButton *)sender {
   
    if (self.passwordTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入密码"];
        return;
    }
    
    self.loginModel = [MNDLoginModel new];
    self.loginModel.userName = self.phoneStr;
    self.loginModel.userLoginPassword = self.passwordTextField.text;
    [self loginWithUser:self.loginModel];
}


//忘记密码
- (IBAction)forgePasswordAction:(UIButton *)sender {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    
    MNDForgotViewController *forgotVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDForgotViewController"];
    [self.navigationController pushViewController:forgotVC animated:YES];
}


- (void)loginWithUser:(MNDLoginModel *)userModel{

    __weak typeof(self) weakSelf = self;
    
    NSDictionary *params = [userModel mj_JSONObject];
    NSLog(@"pp: %@", params);
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_USER_LOGIN parameters:[MNDSign signedParamWithDict:userModel.mj_JSONObject] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"登录成功"];
            MNDLoginUserModel *user = [MNDLoginUserModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf loginOutAction:user];
            
        } else {
            NSDictionary *dic = responseModel.msg;
            [NetworkProgressHUD showHudMsg:dic[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
    
}

- (void)setHTTPHeaders {
    //传userCode
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    if (user.user_code.length > 0) {
        NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", user.user_code] publicKey:RSA_PUBLIC_KEY];
        NSString *unreserved = @"";
        NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
        [allowed addCharactersInString:unreserved];
        
        NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
        [APIManager setGeneralHeaderValue:encodeEncryText forField:@"USERCODE"];
    }
}

- (void)popLogin {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login_state" object:@(YES)];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)loginOutAction:(MNDLoginUserModel *)user {
    
    __weak __typeof(self)weakSelf = self;
    [APIManager sendRequestWithPath:API_USER_LOGOUT parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [UserDefaultsTool removeForKey:kForgetGesture];
//            [NetworkProgressHUD hideHud];
            [weakSelf clearUserContents];
            
            //保存数据库
            [MNDLoginUserModel addOrUpdateUser:user];
            //设置用户标识
            [Bugly setUserIdentifier:user.user_id];
            [weakSelf setHTTPHeaders];
            
            //设置消息推送别名
            [UMessage setAlias:user.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
                if (error) {
                    NSLog(@"设置别名失败: %@", error);
                } else {
                    NSLog(@"设置别名成功: %@", responseObj);
                }
            }];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                NSLog(@"login user: %@", user.description);
                [weakSelf setHTTPHeaders];
                [weakSelf popLogin];
            });
            
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"退出失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)clearUserContents {
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    //删除消息推送设置的别名
    [UMessage removeAlias: user.user_code type:@"minidai" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"删除别名失败: %@", error);
        } else {
            NSLog(@"删除别名成功: %@", responseObject);
        }
    }];
    //清除用户数据
    
    [MNDLoginUserModel deleteAllUserDatas];
    [UserDefaultsTool removeForKey:kOpenDepositAlert];
    //清空手势密码
    [UserDefaultsTool removeForKey:kGesturePassword];
    //清空手势错误次数
    [UserDefaultsTool removeForKey:kErrorCount];
    //关闭手势密码
    [UserDefaultsTool removeForKey:kFingerPassword];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"clearPomeCircleData" object:nil];
    [APIManager setGeneralHeaderValue:nil forField:@"USERCODE"];
    
    [self clearWebViewCookies];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)clearWebViewCookies {
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    //缓存web清除
    //    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
